package com._119yn.host.gst200;

import com._119yn.host.gst200.properties.DtuProperties;
import com._119yn.host.gst200.service.DtuService;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@Slf4j
@EnableAsync
@EnableScheduling
@EnableIntegration
@SpringBootApplication
@RequiredArgsConstructor
public class App implements ApplicationContextAware, ApplicationRunner {

    @Getter
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        App.applicationContext = applicationContext;
    }

    private final DtuProperties dtuProperties;

    private final DtuService dtuService;

    /**
     *
     * 主线程初始化方法执行顺序如下:
     * PostConstruct->ApplicationRunner->CommandLineRunner->ApplicationListener<ApplicationReadyEvent>
     * Scheduled使用的是scheduling调度线程池，并不归主线程管，上面的都是在main线程内按顺序执行的，上一个没有执行完是不会执行下一个的
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (StringUtils.isBlank(dtuProperties.getDtuId())) {
            log.error("DTU_ID未配置，程序退出");
            System.exit(-1);
        }
        try {
            dtuService.importPointTable();
        } catch (Exception e) {
            log.error("加载点表文件失败，程序退出。原因: {}", e.getMessage());
            System.exit(-1);
        }
        if (dtuProperties.isDeviceRegisterEnabled()) {
            if (StringUtils.isBlank(dtuProperties.getDevicePointTableFile())) {
                log.error("设备点表文件未配置，程序退出");
                System.exit(-1);
            }
            dtuService.startDeviceRegister();
            // dtuService.onHostControl(MessageBuilder.withPayload("").build());
            // dtuService.onHostControlError(MessageBuilder.withPayload("").build());
        }
    }

    public static void main(String[] args) {
        if (System.getProperty("java.home") == null) {
            System.setProperty("java.home", ".");
        }
        SpringApplication.run(App.class, args);
    }

}
